package com.summer.safe.utils;


import com.google.common.collect.Lists;
import com.summer.safe.base.TreeNode;
import com.summer.safe.system.entity.Office;
import com.summer.safe.system.entity.User;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 树工具类
 */
public class TreeUtils {

    /**
     * 用户树
     *
     * @param offices
     * @param users
     * @return
     */
    public static List<TreeNode> treeNodes(List<Office> offices, List<User> users) {
        String root = "1";
        List<TreeNode> treeNodes = Lists.newArrayList();
        Set<String> filterSet = new HashSet<>();
        users.forEach(user -> {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(user.getId());
            String pid = CommonUtils.isNotEmpty(user.getOffice()) ? user.getOffice().getId() : root;
            treeNode.setpId(pid);
            filterSet.add(pid);
            treeNode.setName(user.getName());
            treeNode.setIcon("../static/images/user.png");
            treeNode.setType("1");
            treeNodes.add(treeNode);
        });
        List<Office> list = offices.stream().filter(o -> filterSet.contains(o.getId()) || o.getId().equals(root)).collect(Collectors.toList());
        treeNodes.addAll(treeNodes(list));
        return treeNodes;
    }

    /**
     * 默认标准树
     *
     * @param list
     * @return
     */
    public static List<TreeNode> treeNodes(List list) {
        return treeNodes(list, "id", "parentId", "name", "parentIds");
    }

    /**
     * 标准树
     *
     * @param list
     * @return
     */
    public static List<TreeNode> treeNodes(List list, String id, String pid, String name, String pids) {
        List<TreeNode> treeNodes = Lists.newArrayList();
        list.forEach(o -> {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(Reflections.invokeGetter(o, id).toString());
            treeNode.setpId(Reflections.invokeGetter(o, pid).toString());
            treeNode.setName(Reflections.invokeGetter(o, name).toString());
            if (pids != null) {
                treeNode.setpIds(Reflections.invokeGetter(o, pids).toString());
            }
            treeNodes.add(treeNode);
        });
        return treeNodes;
    }

}
